const http = require('http')
const fs = require('fs')
const path = require('path')
const server = http.createServer()

server.on('request', (req, res) => {
  res.setHeader('Access-Control-Allow-Origin', '*') // 设置跨域
  controllers(req, res)
  // readStatic(url, res)
})
// 4.启动服务器
server.listen(8080, () => {
  console.log('start is server')
})

let redis = {}

setInterval(() => { // 用定时器有点草率但是没时间了 先这样凑合做个简单的清楚
  redis = {} // 时间够的话 指定不会这样清,会对每个key进行一个时间绑定。如果时间到期则回清除 类似于session
}, 3000)

const controllers = async (req, res) => {
  const url = req.url
  if (url === '/favicon.ico') return
  if (url === '/') {
    const files = await getFilesName()
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
    let str = ''
    for (var i = 0; i < files.length; i++) {
      str = str + `<a href=${files[i]}>${files[i]}</a><br>`
    }
    const query = 'https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js'
    res.end(`<body><div id='router'></div></body><script src="${query}"></script><script> document.getElementById('router').innerHTML ='${str}'</script> `)
    res.end(`<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        let domA = document.getElementsByTagName("a")
        for(var i=0;i<domA.length;i++){
          let url = http://localhost:8080/+ domA[i].innerHTML
          domA[i].onclick = function(){
            $.ajax({url:url,type:'GET',success:function(data){
              console.log(data)
            }})
          }
        }
    </script>`)
  } else {
    readStatic(url, res)
  }
}

const readStatic = function (url, res) {
  fs.readFile(path.join(__dirname, 'static', url), (_err, data) => { // 路径拼接去static目录下找对应的文件
    const urlItem = url.split('.')
    const Contenttype = mime[urlItem[1]] || 'application/octet-stream'

    if (urlItem[1] === undefined) {
      if (!redis[url]) {
        res.writeHead(200, {
          'Content-Type': 'application/octet-stream',
          'Content-Disposition': `attachment; filename=${urlItem[0]}`
        })
        fs.createReadStream(`${__dirname}/static${url}`).pipe(res)
        redis[url] = true
      } else {
        res.writeHead(403, { 'Content-type': Contenttype })
        res.end()
      }
    } else {
      res.writeHead(200, { 'Content-Type': Contenttype + ';charset=utf-8' })
      res.end(data)
    }
  })
}

const getFilesName = () => {
  return new Promise((resolve, reject) => {
    fs.readdir(`${__dirname}/static`, function (_err, data) {
      if (_err) {
        return reject(_err)
      }
      const item = []
      for (const value of data) {
        item.push(value)
      }
      resolve(item)
    })
  })
}

// const isBuffer = function (str) {
//   return str && typeof str === 'object' && Buffer.isBuffer(str)
// }

const mime = {
  css: 'text/css',
  gif: 'image/gif',
  html: 'text/html',
  ico: 'image/x-icon',
  jpeg: 'image/jpeg',
  jpg: 'image/jpeg',
  js: 'text/javascript',
  json: 'application/json',
  pdf: 'application/pdf',
  png: 'image/png',
  svg: 'image/svg+xml',
  swf: 'application/x-shockwave-flash',
  tiff: 'image/tiff',
  txt: 'text/plain',
  wav: 'audio/x-wav',
  wma: 'audio/x-ms-wma',
  wmv: 'video/x-ms-wmv',
  xml: 'text/xml'
}
